//
//  gengDuoListViewController.m
//  gpos_app
//
//  Created by apple on 2018/10/17.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "gengDuoListViewController.h"
#import "Masonry.h"
#import "GPosAPI.h"
#import "SVProgressHUD.h"
#import "WKProgressHUD.h"
#import "XMRegisterViewController.h"
#import "minerModel.h"
#import "daiShiFangViewCell.h"
#import "MJRefresh.h"

@interface gengDuoListViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong)UITableView * tableView;
@property (nonatomic,strong)WKProgressHUD * hud;
@property (nonatomic,strong)NSMutableArray * modelArr;
@property (nonatomic,assign)NSInteger pageSize;
@property (nonatomic,assign)NSInteger pageNum;

@end

@implementation gengDuoListViewController

//改变状态栏
-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    
}
-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:244/255.0f green:244/255.0f blue:244/255.0f alpha:1];
    self.navigationController.navigationBar.hidden = NO;
    //去掉返回的文字
    self.navigationController.navigationBar.topItem.title = @"";
    self.navigationController.navigationBar.backgroundColor=[UIColor whiteColor];
    self.navigationController.navigationBar.tintColor=[UIColor blackColor];
    self.title = @"释放列表";
    [self loadData];
    
}

- (void)loadData{
    __weak typeof(self) weakSelf = self;
    self.pageSize = 10;
    self.pageNum = 1;
    self.modelArr = [[NSMutableArray alloc] init];
    int user = [[[NSUserDefaults standardUserDefaults] objectForKey:@"userId"] intValue];
    NSDictionary * param = @{@"userId" : @(user),
                             @"pageSize" : @(self.pageSize),
                             @"pageNum" : @(self.pageNum)
                             };
    [GPosAPI requestViewDetailListWithParams:param andCallback:^(id obj) {
        NSLog(@"储存列表---%@",obj);
        if (obj == nil) {
             weakSelf.hud=[WKProgressHUD popMessage:@"请求失败" inView:self.view duration:1 animated:YES];
        }else {
            
            if ([[obj objectForKey:@"code"] integerValue] ==200) {
                NSArray * arr = [[NSArray alloc] init];
                arr = [obj objectForKey:@"data"];
                for (NSDictionary * dic in arr) {
                    minerModel *model = [[minerModel alloc] init];
                    NSDecimalNumber * number = [dic objectForKey:@"actual"];
                    NSDecimalNumber * numbeOne = [dic objectForKey:@"bar"];
                    NSDecimalNumber * numberTwo = [dic objectForKey:@"storage"];
                    NSDecimalNumber * numberTw = [dic objectForKey:@"gain"];
                    model.actual = [NSString stringWithFormat:@"%@",@(number.floatValue)];
                    model.bar = [NSString stringWithFormat:@"%@",@(numbeOne.floatValue)];
                    model.created = [dic objectForKey:@"created"];
                    model.storage = [NSString stringWithFormat:@"%@",@(numberTwo.floatValue)];
                    model.gain = [NSString stringWithFormat:@"%@",@(numberTw.floatValue)];
                    [weakSelf.modelArr addObject:model];
                }
                [weakSelf.tableView reloadData];
            }else if ([[obj objectForKey:@"code"] integerValue] ==401 || [[obj objectForKey:@"code"] intValue] == 402){
                UIStoryboard *mainStory = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"passWord"];
                //storyboard里的ID
                XMRegisterViewController *vc = [mainStory instantiateInitialViewController];
                vc.navigationController.navigationBarHidden=NO;
                //                    //设置当前窗口的根控制器
                
                [UIApplication sharedApplication].keyWindow.rootViewController=vc;
                [SVProgressHUD showInfoWithStatus:[obj objectForKey:@"message"]];
                [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
                [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeFlat];
                
            }else {
                
                [SVProgressHUD showErrorWithStatus:[obj objectForKey:@"message"]];
                [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
                [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeFlat];
                
            }
            
        }
        
        [weakSelf UIloadView];
    }];
    
}

- (void)UIloadView{
    
    self.tableView = [[UITableView alloc] init];
    self.tableView.backgroundColor = [UIColor colorWithRed:244/255.0f green:244/255.0f blue:244/255.0f alpha:1];
//    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.mj_footer=[MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreShopss)];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).with.offset(kNavbarHeight);
        make.left.equalTo(self.view).with.offset(0);
        make.right.equalTo(self.view).with.offset(0);
        make.bottom.equalTo(self.view).with.offset(-kBottomSafeHeight);
    }];
    UIView * footerView = [[UIView alloc] init];
    self.tableView.tableFooterView = footerView;
    
    
}

//上拉加载更多
- (void)loadMoreShopss{
    __weak typeof(self) weakSelf = self;
    self.pageNum ++;
    int user = [[[NSUserDefaults standardUserDefaults] objectForKey:@"userId"] intValue];
    NSDictionary * param = @{@"userId" : @(user),
                             @"pageSize" : @(self.pageSize),
                             @"pageNum" : @(self.pageNum)
                             };
    [GPosAPI requestViewDetailListWithParams:param andCallback:^(id obj) {
        NSLog(@"储存列表---%@",obj);
        if (obj == nil) {
            [weakSelf.tableView.mj_footer endRefreshing];
             weakSelf.hud=[WKProgressHUD popMessage:@"请求失败" inView:self.view duration:1 animated:YES];
        }else {
            
            if ([[obj objectForKey:@"code"] integerValue] ==200) {
                NSArray * arr = [[NSArray alloc] init];
                arr = [obj objectForKey:@"data"];
                for (NSDictionary * dic in arr) {
                    minerModel *model = [[minerModel alloc] init];
                    NSDecimalNumber * number = [dic objectForKey:@"actual"];
                    NSDecimalNumber * numbeOne = [dic objectForKey:@"bar"];
                    NSDecimalNumber * numberTwo = [dic objectForKey:@"storage"];
                    NSDecimalNumber * numberTw = [dic objectForKey:@"gain"];
                    model.actual = [NSString stringWithFormat:@"%@",@(number.floatValue)];
                    model.bar = [NSString stringWithFormat:@"%@",@(numbeOne.floatValue)];
                    model.created = [dic objectForKey:@"created"];
                    model.storage = [NSString stringWithFormat:@"%@",@(numberTwo.floatValue)];
                    model.gain = [NSString stringWithFormat:@"%@",@(numberTw.floatValue)];
                    [weakSelf.modelArr addObject:model];
                }
                [weakSelf.tableView reloadData];
                [weakSelf.tableView.mj_footer endRefreshing];
            }else if ([[obj objectForKey:@"code"] integerValue] ==401 || [[obj objectForKey:@"code"] intValue] == 402){
                UIStoryboard *mainStory = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"passWord"];
                //storyboard里的ID
                XMRegisterViewController *vc = [mainStory instantiateInitialViewController];
                vc.navigationController.navigationBarHidden=NO;
                //                    //设置当前窗口的根控制器
                
                [UIApplication sharedApplication].keyWindow.rootViewController=vc;
                [SVProgressHUD showInfoWithStatus:[obj objectForKey:@"message"]];
                [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
                [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeFlat];
                
            }else {
                
                [SVProgressHUD showErrorWithStatus:[obj objectForKey:@"message"]];
                [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
                [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeFlat];
                
            }
            
        }
        
        
    }];
    
    
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.modelArr.count;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{//rankingCell
    
    
    daiShiFangViewCell * cell = [[daiShiFangViewCell alloc] init];
    
    cell = [tableView dequeueReusableCellWithIdentifier:@"daishifangCell"];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"daiShiFangViewCell" owner:self options:nil] firstObject];
    }
    
    //渐变色
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = CGRectMake(0, 0, 130, 5);
    //设置渐变颜色数组,可以加透明度的渐变
    gradientLayer.colors = @[(__bridge id)[UIColor colorWithWhite:0 alpha:0.3].CGColor,(__bridge id)[UIColor colorWithWhite:0 alpha:1].CGColor];
    //设置渐变区域的起始和终止位置（范围为0-1）
    gradientLayer.startPoint = CGPointMake(1, 0);
    gradientLayer.endPoint = CGPointMake(0.5, 0);
    //设置蒙版，用来改变layer的透明度
    [cell.progressView.layer setMask:gradientLayer];
    
    
    cell.topLabel.text = [NSString stringWithFormat:@"%@（实存:%@ 放大:%@倍）",[self.modelArr[indexPath.row] storage],[self.modelArr[indexPath.row] actual],[self.modelArr[indexPath.row] gain]];
    
    // timeStampString 是服务器返回的13位时间戳
    NSString *timeStampString  = [self.modelArr[indexPath.row] created];
    
    // iOS 生成的时间戳是10位
    NSTimeInterval interval=[timeStampString doubleValue] / 1000.0;
    NSDate *date  = [NSDate dateWithTimeIntervalSince1970:interval];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateString    = [formatter stringFromDate: date];
    
    
    cell.bottomLabel.text = dateString;
    double num = (double)[[self.modelArr[indexPath.row] bar] doubleValue]*100;
    NSString * str = @"%";
    cell.progressView.progress = [self.modelArr[indexPath.row] bar].floatValue;
    //    NSLog(@"---cueng--%f",[self.modelArr[indexPath.row] bar].floatValue);
    cell.baifenbiLabel.text = [NSString stringWithFormat:@"%@%@",@((float)num).description,str];
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 70;
}

@end
